package com.prabhakar.taxiclubapp;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CustomerRegistrationActivity extends Activity {

	//progress bar..
	ProgressDialog pDialog;
	JSONParser jsonParser = new JSONParser();

	String name="";
	String email="";
	String phoneNumber="";
	String password="";
	String confirmPassword="";

	private static String TAG ="CustomerRegistrationActivity";
	private static final String Package_Path ="com.prabhakar.taxiclubapp";
	private static final String RestActivity_Classpath = "com.prabhakar.taxiclubapp.RestServicesClient_UsingJsonPost";
	private static final String TAG_SUCCESS = "success";
	private static final int Result_Code = 007;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.customer_registration);

		final EditText editText1 = (EditText)findViewById(R.id.cust_name);
		final EditText editText2 = (EditText)findViewById(R.id.cust_phoneNumber);
		final EditText editText3 = (EditText)findViewById(R.id.cust_email);
		final EditText editText4 = (EditText)findViewById(R.id.password);
		final EditText editText5 = (EditText)findViewById(R.id.confirm_password);

		Button submit = (Button)findViewById(R.id.submitBtn);
		submit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				boolean inValidFormData = false;

				if(editText1.getText().length()==0 || editText2.getText().length()<10 || editText2.getText().length()>10 || editText3.getText().length()==0 || !android.util.Patterns.EMAIL_ADDRESS.matcher(editText3.getText()).matches()){

					if(editText1.getText().length()==0){
						inValidFormData = true;
						editText1.setError(Constants.NAME_REQUIRED);
					}else{
						name = editText1.getText().toString();
					}

					if(editText2.getText().length()==0){
						inValidFormData = true;
						editText2.setError(Constants.PHONENUMBER_REQUIRED);
					}else if(editText2.getText().length()<10 || editText2.getText().length()>10){
						inValidFormData = true;
						editText2.setError(Constants.VALID_PHONENUMBER_REQUIRED);
					}else{
						phoneNumber = editText2.getText().toString();
					}

					if(editText3.getText().length()==0){
						inValidFormData = true;
						editText3.setError(Constants.EMAIL_REQUIRED);
					}else if(!android.util.Patterns.EMAIL_ADDRESS.matcher(editText3.getText()).matches()){
						inValidFormData = true;
						editText3.setError(Constants.VALID_EMAIL_REQUIRED);
					}else{
						email = editText3.getText().toString();
					}

					if(editText4.getText().length()==0){
						inValidFormData = true;
						editText4.setError(Constants.PASSWORD_REQUIRED);
					}else{
						password = editText4.getText().toString();
					}
					
					if(editText5.getText().length()==0){
						inValidFormData = true;
						editText5.setError(Constants.CONFIRMATION_PASSWORD_REQUIRED);
					}else if(editText5.getText().toString().equalsIgnoreCase(editText4.getText().toString())){
						inValidFormData = true;
						editText5.setError(Constants.PASSWORDS_DO_NOT_MATCH);
					}else{
						confirmPassword = editText5.getText().toString();
					}
				}
				
				Log.v(TAG,"name => "+name +" phoneNumber => "+phoneNumber +" email => "+email
						+" password => "+password+" confirm Password => "+confirmPassword);
				
				if(!inValidFormData){		
					//ASYNC REST-CLIENT call..._ACCN TO PHPSCRIPT
					new  AsyncCustomerRegistration().execute();
				}
			}
		});
		
	}

	/*public void doCustomerRegistration1(View v){

		Log.v(TAG,">>>>>>>>>>> INside doCustomerRegistration <<<<<<<<<");

		Log.v(TAG," name >> "+name +" email >> "+email + " phoneNumber >> "+phoneNumber);

		REST-CLIENT call --to Register the Customer 
	//	new RestServicesClient_UsingJsonPost().processCustomerRegistration(jsonObj);
		//	######	new AsyncCustomerRegistration().execute();

	Intent cust_registrationIntent = new Intent();
	//cust_registrationIntent.setClass(getApplicationContext(), RestServicesClient_UsingJsonPost.class);
	cust_registrationIntent.setComponent(new ComponentName(Package_Path,RestActivity_Classpath));
	cust_registrationIntent.putExtra("Activity_Name", TAG);
//	add json data to this intent & send..

	this.startActivityForResult(cust_registrationIntent, Result_Code);

	}
	 */	

	/*@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.v(TAG, ">>> Inside onActivityResult of CustomerRegistrationActivity ");
		if(resultCode == Result_Code){

		}
	}*/

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.customer_registration, menu);
		return true;
	}



	/*
	 * private Class tht runs  the AsynTask
	 */
	private class AsyncCustomerRegistration extends AsyncTask <String , String, String>{

		private static final String Tag ="AsyncP2PBooking";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(CustomerRegistrationActivity.this);
			pDialog.setMessage("Processing Customer Registration details. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
			Log.v(Tag ,"Inside onPreExecute ");
		}

		@Override
		protected String doInBackground(String... args) {

			String response = "";
			Log.v(Tag ," >>>>> Inside doInBackground > ");

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("name", name));
			params.add(new BasicNameValuePair("phoneNumber", phoneNumber));
			params.add(new BasicNameValuePair("email", email));
			params.add(new BasicNameValuePair("password", password));
			
			// getting JSON Object to store RESPONSE..
			// Note that taxi-Booking url accepts POST method
			JSONObject json = null;				
			json = jsonParser.makeHttpRequest(Constants.TC_RESTURL_CUSTOMER_REGISTRATION,"POST", params);
			Log.d("Customer Registration Response", json.toString());

			// check for success tag
			try {
				int success = json.getInt(Constants.TAG_SUCCESS);
				response = json.getString(Constants.TAG_MESSAGE);
				if (success == 1) {
					// successfully registered customer..!!!

					//    Intent i = new Intent(getApplicationContext(), WelcomeActivity.class);
					//    startActivity(i);

					// closing this screen
					finish();
				} else if(success == 0 && response.equalsIgnoreCase(Constants.REST_DUPLICATE_CUSTOMER_REGISTRATION_RESPONSE))
				{
					//## DUPLICATE_CUSTOMER_REGISTRATION -ATTEMPT..!!!
				//	DO SOMETHING HERE..

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return response;

		}

		@Override
		protected void onPostExecute(String response) {
			super.onPostExecute(response);
			pDialog.setMessage(response);
			pDialog.dismiss();
			Log.v(Tag,"RESPONSE /result  recevd in onPostExecute() >> "+response);

		}

	}
}
